package com.kapcb.secure.configuration.core;

import com.kapcb.secure.configuration.enums.AlgorithmType;
import com.kapcb.secure.configuration.enums.EncodeType;
import com.kapcb.secure.configuration.filter.SecureUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * <a>Title: RsaEncryptor </a>
 * <a>Author: kapcb <a>
 * <a>Description: RsaEncryptor <a>
 *
 * @author Kpacb
 * @version 1.0
 * @date 2024/5/5 9:48
 * @since 1.0
 */
public class RsaEncryptor extends AbstractSecurerProvider {

    private final EncryptContext encryptContext;

    public RsaEncryptor(EncryptContext encryptContext) {
        super(encryptContext);
        String privateKey = encryptContext.getPrivateKey();
        String publicKey = encryptContext.getPublicKey();
        if (StringUtils.isAnyEmpty(privateKey, publicKey)) {
            throw new IllegalArgumentException("RSA公私钥均需要提供，公钥加密，私钥解密。");
        }
        this.encryptContext = encryptContext;
    }

    /**
     * 获得当前算法
     */
    @Override
    public AlgorithmType algorithm() {
        return AlgorithmType.RSA;
    }

    /**
     * 加密
     *
     * @param value      待加密字符串
     * @param encodeType 加密后的编码格式
     */
    @Override
    public String encrypt(String value, EncodeType encodeType) {
        if (encodeType == EncodeType.HEX) {
            return SecureUtils.encryptByRsaHex(value, encryptContext.getPublicKey());
        } else {
            return SecureUtils.encryptByRsa(value, encryptContext.getPublicKey());
        }
    }

    /**
     * 解密
     *
     * @param value 待加密字符串
     * @return
     */
    @Override
    public String decrypt(String value) {
        return SecureUtils.decryptByRsa(value, encryptContext.getPrivateKey());
    }
}
